// 购物车模块

import { defineStore } from "pinia";
import { ref,computed } from "vue";
import { useUserStore } from "@/stores/user.js";
import { insertCart , findNewCartListApi,delCartAPI,mergeCartAPI} from "@/apis/cart.js"
export const useCartStore = defineStore('cart',()=> {

// 用户信息判断是否登录
const userStore = useUserStore()
const IsLogin = computed(() => userStore.userInfo.token)


  // 建立购物车
const cartList = ref([])

// 获取商品
const getCartList = async () => {
  const res = await findNewCartListApi()
  cartList.value = res.result
}

//添加商品
const addItemTocar = async (goods) => {
  const {skuId , count} = goods
  if(IsLogin){
    await insertCart({skuId,count})
    getCartList()
    console.log(cartList.value)
  }
  else {
      // 购物车中有这个商品

    const item = cartList.value.find((item) => goods.skuId === item.skuId)
    if(item){
      item.count += goods.count
    } else {
      cartList.value.push(goods)
    }
  }


}

// 清除购物车
const delCart = async (skuId) => {

  if(IsLogin.value){
    //调用接口实现接口购物车的删除功能
    await delCartAPI([skuId])
    getCartList()
    console.log("删除后 购物车还剩下" + cartList.value)
  } else {

    //思路：
    //1 找到要删除项的下标值 -splice
    //2.使用数组的过滤方法
    const idx = cartList.value.findIndex((item) => skuId == item.skuId)
    cartList.value.splice(idx,1)
  }


}


//计算属性
//1.总的数量 所有项的count子和
const allCount = computed(() => cartList.value.reduce((accumulator,currentValue) => accumulator + currentValue.count ,0))
//2.总价 所有项的count*price累加
const allPrice = computed(() => cartList.value.reduce((accumulator,currentValue) => accumulator + currentValue.count * currentValue.price,0))


// 取消商品在购物车
const checkItem = (skuId,selected) =>{
  const item = cartList.value.find((item) => skuId == item.skuId)
  item.selected = selected
}


// 监听选择框是否为全选状态
const AllSelected = computed(() => cartList.value.every((item) => item.selected))

// 选择框全部选中
const checkAll = (selected) =>{
  cartList.value.forEach(item => item.selected = selected)
}

//计算已选中的商品数量
const selectedNumber = computed(() => cartList.value.filter(item => item.selected == true).reduce((pre,item) => pre + item.count,0))
const selectedPrice = computed(()=> cartList.value.filter(item => item.selected == true).reduce((pre,item) => pre + item.price * item.count , 0))


// 清空购物车
const clearCar = () => {
  cartList.value = []
}

// 合并购物车操作
const mergeCart = async() => {
  mergeCartAPI(cartList.value,map(item =>{
    return {
      skuid: item.skuId,
      selected: item.selected,
      count: item.count
    }
  }))
  getCartList()
}

// 更新购物车







//返回出去
return {
  cartList,
  allCount,
  allPrice,
  AllSelected,
  selectedNumber,
  selectedPrice,
  getCartList,
  checkAll,
  checkItem,
  delCart,
  addItemTocar,
  clearCar,
  mergeCart
}


},{
  persist:true
})
